import axios from 'axios'
import useToken from '../stores/token'
import { ElLoading } from 'element-plus'
import notification from '@/utils/notification'
import router from '../router'

var loadingInstance = null
const request = axios.create({
	timeout: 2000
})

request.interceptors.request.use(config => {
	loadingInstance = ElLoading.service()
	const {
		token
	} = useToken()
	console.log(token)
	if (token) {
		config.headers.jwt = token
	}
	return config
})

request.interceptors.response.use(
	response => {
		loadingInstance.close()
		const {
			errno,
			data,
			errmsg
		} = response.data
		if (errno === 0) {
			if (errmsg !== '') {
				notification({
					message: errmsg,
					type: 'success'
				})
			}
			return data || true
		}
		notification({
			message: errmsg,
			type: 'error'
		})
		if (errno === 2) {
			router.push({
				name: 'login'
			})
		}
		return false
	},
	error => {
		loadingInstance.close()
		notification({
			message: '请求失败',
			type: 'error'
		})
		console.log(error)
	}
)

export default request